package com.example.aslongastoday.ui.tomato_clock;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.aslongastoday.R;

import java.util.Objects;

public class TomatoClockFragment extends Fragment {

    private TomatoClockService tomatoClockService;
    private boolean isBound = false;
    private BackgroundMusicService musicService;
    private boolean isMusicServiceBound = false;
    public ProgressBar progressBar;
    private Button btn_start;
    private Button btn_cancel;
    private TextView clockView;
    private int minute;
    private int second;
    private NumberPicker minute_picker;
    private NumberPicker second_picker;
    private boolean isRunning = false;
    private ImageView iv_music;
    static final MediaPlayer[] mediaPlayer = {null};


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_tomato_clock, container, false);
        progressBar = root.findViewById(R.id.progress_bar);
        btn_start = root.findViewById(R.id.btn_start_pause);
        btn_cancel = root.findViewById(R.id.btn_cancel);
        clockView = root.findViewById(R.id.text_tomato_clock);
        minute_picker = root.findViewById(R.id.minute_picker);
        second_picker = root.findViewById(R.id.second_picker);
        iv_music = root.findViewById(R.id.iv_music);

        minute_picker.setMinValue(0);
        minute_picker.setMaxValue(60);
        minute_picker.setValue(25);
        minute_picker.setWrapSelectorWheel(true);
        second_picker.setMinValue(0);
        second_picker.setMaxValue(59);
        second_picker.setValue(0);
        second_picker.setWrapSelectorWheel(true);

        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String startButtonText = btn_start.getText().toString();
                if (startButtonText.equals("开始")){
                    minute = minute_picker.getValue();
                    second = second_picker.getValue();
                    if(minute==0 && second==0){
                        //错误
                        Toast.makeText(getContext(), "请选择有效计时", Toast.LENGTH_SHORT).show();
                    }
                    else if(minute==0 && second<10){
                        //时间过短
                        Toast.makeText(getContext(), "时间太短了，再考虑一下吧", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        if (tomatoClockService.countDownTimer != null) {
                            tomatoClockService.countDownTimer.cancel();
                        }
                        tomatoClockService.countDownTimer = new CustomCountDownTimer((minute * 60 + second) * 1000, 1000, progressBar, clockView, btn_start);
                        tomatoClockService.countDownTimer.start();
                        isRunning = true;
                        btn_start.setText("暂停");
                    }
                }
                else if (isRunning) {
                    tomatoClockService.countDownTimer.pause();
                    isRunning = false;
                    btn_start.setText("继续");
                } else {
                    tomatoClockService.countDownTimer.resume();
                    isRunning = true;
                    btn_start.setText("暂停");
                }
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isRunning && tomatoClockService.countDownTimer != null){
                    tomatoClockService.countDownTimer.pause();
                    long millisUntilFinished = tomatoClockService.countDownTimer.getMillisUntilFinished();
                    long millisInFuture = tomatoClockService.countDownTimer.getMillisInFuture();
                    long millisHasFinishedMin = (millisInFuture - millisUntilFinished) / 1000 / 60;
                    long millisHasFinishedSec = (millisInFuture - millisUntilFinished) / 1000 % 60;
                    showCancelDialog("已专注" + millisHasFinishedMin + "分" + millisHasFinishedSec + "秒" + "，是否提前结束专注");
                }
            }
        });

        //TODO 音乐按钮监听事件
        iv_music.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), BackgroundMusicService.class);
                getActivity().startService(intent);

                if (mediaPlayer[0] == null) {
                    mediaPlayer[0] = MediaPlayer.create(getContext(), R.raw.thanks_music);
                    mediaPlayer[0].setLooping(true);
                    mediaPlayer[0].start();
                    iv_music.setImageResource(R.drawable.icon_music_open);
                }else {
                    if (mediaPlayer[0].isPlaying()) {
                        mediaPlayer[0].pause();
                        iv_music.setImageResource(R.drawable.icon_music_close);
                    } else {
                        mediaPlayer[0].start();
                        iv_music.setImageResource(R.drawable.icon_music_open);
                    }
                }
            }
        });
        return root;
    }


    public void onDestroyView() {
        super.onDestroyView();
        //这里存在空指针异常导致从其它的fragment切换的时候这一句会寄
        //countDownTimer.cancel();
    }


    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            TomatoClockService.LocalBinder binder = (TomatoClockService.LocalBinder) service;
            tomatoClockService = binder.getService();
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
        }
    };
    private ServiceConnection musicServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            BackgroundMusicService.LocalBinder musicBinder = (BackgroundMusicService.LocalBinder) service;
            isMusicServiceBound = true;
            musicService = musicBinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isMusicServiceBound = false;
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        Intent intent = new Intent(getActivity(), TomatoClockService.class);
        Objects.requireNonNull(getActivity()).bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
        Intent musicIntent = new Intent(getActivity(), BackgroundMusicService.class);
        getActivity().bindService(musicIntent, musicServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (isBound) {
            //getActivity().unbindService(serviceConnection);
            //isBound = false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    private void updateUI() {
        if (isBound && tomatoClockService.countDownTimer != null) {
            long millisUntilFinished = tomatoClockService.countDownTimer.getMillisUntilFinished();
            long millisInFuture = tomatoClockService.countDownTimer.getMillisInFuture();
            if(millisUntilFinished==0){
                isRunning = false;
                progressBar.setProgress(100);
                clockView.setText("25:00");
                btn_start.setText("开始");
                Toast.makeText(tomatoClockService, "倒计时已结束，请重新开始", Toast.LENGTH_SHORT).show();
            }
            else {
                tomatoClockService.countDownTimer.cancel();
                tomatoClockService.countDownTimer = new CustomCountDownTimer(millisUntilFinished-500, millisInFuture, 1000, progressBar, clockView, btn_start);
                tomatoClockService.countDownTimer.start();
                isRunning = true;
                btn_start.setText("暂停");
                if((millisInFuture-millisUntilFinished) <= 30000){
                    String text = "检测到退出番茄钟，专注时长不足30s \n是否结束专注";
                    showCancelDialog(text);
                } else if (millisUntilFinished <= 30000) {
                    String text = "检测到退出番茄钟，剩余时间不足30s \n是否结束专注";
                    showCancelDialog(text);
                }
            }
        }
        //音乐播放键
        if(mediaPlayer[0] == null){
            iv_music.setImageResource(R.drawable.icon_music_close);
        }else{
            if(mediaPlayer[0].isPlaying()){
                iv_music.setImageResource(R.drawable.icon_music_open);
            }else {
                iv_music.setImageResource(R.drawable.icon_music_close);
            }
        }
    }

    private void showCancelDialog(String text) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("取消专注");
        builder.setMessage(text);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tomatoClockService.countDownTimer.cancel();
                tomatoClockService.countDownTimer = null;
                progressBar.setProgress(100);
                clockView.setText("25:00");
                btn_start.setText("开始");
                // 退出的时候检测一下是否有在播放背景音乐，如果有的话，就关闭~
                if (mediaPlayer[0] != null){
                    mediaPlayer[0].release();
                    mediaPlayer[0] = null;
                    iv_music.setImageResource(R.drawable.icon_music_close);
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                tomatoClockService.countDownTimer.resume();
            }
        });
        builder.show();
    }

}

